const http = require('http');
const url = require('url')
const path = require('path')
const fs = require('fs')
const mime = require('mime')

const server = http.createServer((req, res) => {
  // 01 路径处理
  let {pathname, query} = url.parse(req.url)
  pathname = decodeURIComponent(pathname)
  let absPath = path.join(__dirname, pathname)
  // console.log(absPath)
  // 02 目标资源的状态处理
  fs.stat(absPath, (err, stat) => {
    if (err) {
      res.statusCode = 404
      res.end('Not found')
      return
    }
    if (stat.isFile()) {
      fs.readFile(absPath, (err, data) => {
        res.setHeader('Content-Type', `${mime.getType(absPath)};charset=utf-8`)
        res.end(data)
      })
    } else {
      fs.readFile(path.join(absPath, 'index.html'), (err, data) => {
        res.setHeader('Content-Type', `${mime.getType(path.join(absPath, 'index.html'))};charset=utf-8`)
        res.end(data)
      })
    }
  }) 
})

server.listen(1234, () =>{
  console.log('server listening')
})